from appium.webdriver.webdriver import WebDriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.common.exceptions import NoSuchElementException
import time


class BasePage:
    def __init__(self, driver: WebDriver):
        self.driver = driver

    def find_element(self, locator, timeout=10):
        """通用元素定位方法"""
        try:
            return self.driver.find_element(*locator)
        except NoSuchElementException:
            self._take_screenshot("element_not_found")
            raise

    def click(self, locator):
        """点击操作"""
        element = self.find_element(locator)
        element.click()

    def input_text(self, locator, text):
        """输入文本"""
        element = self.find_element(locator)
        element.clear()
        element.send_keys(text)

    def swipe_up(self, duration=500):
        """向上滑动"""
        size = self.driver.get_window_size()
        start_x = size['width'] * 0.5
        start_y = size['height'] * 0.8
        end_y = size['height'] * 0.2
        self.driver.swipe(start_x, start_y, start_x, end_y, duration)

    def _take_screenshot(self, name):
        """截图方法"""
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        filename = f"{name}_{timestamp}.png"
        self.driver.save_screenshot(filename)
        return filename